package cn.kaiux.bigdata.homework.week05_06

import org.apache.hadoop.fs.Path
import scopt.OptionParser

import java.net.URI

/**
 * @author kaiux@foxmail.com
 * @date 2022/6/9 15:51
 */
object DistCPOptionsParsing {

  def parse(args: Array[String]): Config = {

    val parser = new OptionParser[Config]("") {
      opt[Boolean]('i', "ignoreFailures")
        .action((i, c) => c.copy(ignoreFailures = i))
        .text("Ignore failures")

      opt[Int]('m', "maxConcurrence")
        .action((m, c) => c.copy(maxConcurrence = m))
        .text("Max number of concurrence to use for job")

      help("help").text("prints this usage text")

      arg[String]("[source_path...] <target_path>")
        .unbounded()
        .action((u, c) => c.copy(URIs = c.URIs :+ new URI(u)))

    }

    parser.parse(args, Config()) match {
      case Some(config) =>
        config.validate()
        config
      case _ =>
        throw new RuntimeException("Failed to parse arguments")
    }
  }

  def main(args: Array[String]): Unit = {
    val config = parse(args)
    println(config)
    println(config.getPaths)
  }

}

case class Config(ignoreFailures: Boolean = false,
                  maxConcurrence: Int = 1,
                  URIs: Seq[URI] = Seq.empty) {

  // 验证参数，路径必须大于2个（多个输入和一个输出）
  def validate(): Unit = {
    require(URIs.length >= 2, "Paths must be specified for source and target")
    require(maxConcurrence > 0, "Max concurrence must be greater than 0")
  }

  // 解析输入和输出路径
  def getPaths: (Seq[Path], Path) = {
    URIs.reverse match {
      case d :: s :: ts =>
        ((s :: ts).reverse.map(u => new Path(u)), new Path(d))
      case _ => throw new RuntimeException("Invalid paths")
    }
  }

}